<?php

namespace backend\models;

use Yii;
use backend\models\Admin_Node;
use backend\models\AdminRoleNode;
use yii\data\Pagination;

/**
 * This is the model class for table "admin_role".
 *
 * @property string $id
 * @property string $name
 */
class AdminRole extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin_role';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['name'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '角色名',
            'node_name' => '权限名称',
            'node_id' => 'Node_id',
        ];
    }
    /*
    *@查询用户拥有角色
     */
    public function userRole($user_id)
    {
        //查询分页后用户角色ID
        $user_role = Yii::$app->db->createCommand('select * from admin_user_role where user_id in ('.implode(',',$user_id).')')->queryAll();
        $role_name = '';
        if(!empty($user_role))
        {
            //用户拥有角色ID
            $role = [];
            foreach ($user_role as $k => $v) {
                $role[$v['user_id']][] = $v['role_id'];
            }
            //用户角色名称
            foreach ($role as $k => $v) {
                $role_name[$k] = implode(',',$this->arr2Arr1(Yii::$app->db->createCommand('select name from admin_role where id in ('.implode(',',$v).')')->queryAll(),'name'));
            }
        }
        return $role_name;
    }
    /**
     * @查询全部角色
     */
    public function findRole()
    {
        $role = $this::find();
        $Page = new Pagination([
            'defaultPageSize' => 7,
            'totalCount' => $role->count(),
        ]);

        $role = $role
            ->offset($Page->offset)
            ->limit($Page->limit)
            ->asArray()
            ->all();
        $data['role_data'] = $this->roleNode($role);
        $data['page'] = $Page;
        return $data;
    }

    /*
    *@添加角色
     */
    public function roleAdd($data,$id='')
    {
        
        
        $this->name = $data['AdminRole']['name'];
        if ($id) {
            $this->id = $id;
        }
        if ($this->save()) {
            
            $id = $this->attributes['id'];
            if(empty($data['AdminRole']['node_id'])){
                return $id;
            }else
            {
                $roleNode = $data['AdminRole']['node_id'];
                return $this->NodeAdd($roleNode,$id);
            }
        }
        
    }

    /*
    *@修改角色
     */
    public function roleUpdate($data,$id)
    {
        $obj = $this->findOne($id);
        $obj->name = $data['name'];
        if ($obj->save()) {
            $res['err'] = true;
            $this->deleteRolenode($id);
            if (!empty($data['node_id'])) {
                $res['msg'] = $this->nodeAdd($data['node_id'],$id);
            }else{
                $res['msg'] = '修改成功';
            }
        }else{
            $res['err'] = false;
            $res['msg'] = '修改失败';
        }
        return $res;
    }

    /*
    *@添加角色关系表
     */
    public function nodeAdd($data,$id)
    {
        $arr = [];
        foreach ($data as $k => $v) {
            array_push($arr,'('.$id.','.$v.')');
        }
        $sql = 'insert into admin_role_node values '.implode(',',$arr);
        return Yii::$app->db->createCommand($sql)->execute();
    }


    /**
     * @角色删除
     */
    public function role_delete($id='')
    {
        $obj = $this->findOne($id);
        if(is_object($obj) && $obj->delete()){
            $this->deleteRolenode($id);
            return true;
        }else
        {
            return false;
        }
    }

    /*
    *@删除角色关系表
     */
    public function deleteRolenode($id)
    {
        $sql = 'delete from admin_role_node where role_id ='.$id;
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * @查询关联表
     */
    public function roleNode($arr)
    {
        
        $model = AdminRoleNode::find();
        if ($this->getmaxdim($arr) == 1) {
            
            $arr['node_id'] = implode(',',$this->arr2Arr1($model
                                        ->select('node_id')
                                        ->where(['role_id'=>$arr['id']])
                                        ->asArray()
                                        ->all(),'node_id'));
        // return $arr;
            $array = $this->Node($arr);
        }else{

            foreach ($arr as $k => $v) {
                $arr[$k]['node_id'] = implode(',',$this->arr2Arr1($model
                                            ->select('node_id')
                                            ->where(['role_id'=>$v['id']])
                                            ->asArray()
                                            ->all(),'node_id'));
            }
            $array = $this->Node($arr);
        }
        // return $arr;
        return $array;
    }

    /**
     * @查询权限表
     */
    public function Node($arr)
    {
        $array = [];
        if ($this->getmaxdim($arr) == 1) {
            if ($arr['node_id'] != '') {
                $sql = 'select id,name from admin_node where id in ('.$arr['node_id'].')';
                $array['name'] = $arr['name'];
                $array['id'] = $arr['id'];
                $data = Yii::$app->db->createCommand($sql)->queryAll();
                $array['node_id'] = implode(',',$this->arr2Arr1($data,'id'));
            }else{
                $array['name'] = $arr['name'];
                $array['id'] = $arr['id'];
                $array['node_id'] = '';
            }
        }else{

            foreach ($arr as $k => $v) {
                if ($v['node_id'] != '') {
                    $sql = 'select name from admin_node where id in ('.$v['node_id'].')';
                    $array[$k]['name'] = $v['name'];
                    $array[$k]['id'] = $v['id'];
                    $array[$k]['node_id'] = implode(',',$this->arr2Arr1(Yii::$app->db->createCommand($sql)->queryAll(),'name'));
                }else{
                    $array[$k]['name'] = $arr[$k]['name'];
                    $array[$k]['id'] = $arr[$k]['id'];
                    $array[$k]['node_id'] = '';
                }
                
            }
        }
        return $array;
    }

    /**
     * @对象转换为二维数组
     */
    public function obj2ArrAll($obj)
    {
        $arr = [];
        foreach ($obj as $k => $v) {
            foreach ($v as $key => $value) {
                $arr[$k][$key] = $value;
            }
        }
        return $arr;
    }


    /**
     * @二维转换为一维数组
     */
    public function arr2Arr1($obj,$key)
    {
        $arr = [];
        foreach ($obj as $k => $v) {
            array_push($arr,$v[$key]);
        }
        return $arr;
    }

    /*
    *@查询一条数据
     */
    
    public function roleOne($id)
    {
        $obj = $this->find()->where(['id'=>$id])->asArray()->one();
        if(is_array($obj)){
            //把对象转换为数组
            $data = $this->roleNode($obj);
            $json['error'] = true;
            $json['msg']   = $data;
        }else{

            $json['error'] = false;
            $json['msg']   = '该条数据错误';
        }
        return json_encode($json);
    }
    

    /*
    *@获取数组的维度
     */
    function getmaxdim($vDim)
    {
      if(!is_array($vDim)) return 0;
      else
      {
        $max1 = 0;
        foreach($vDim as $item1)
        {
         $t1 = $this->getmaxdim($item1);
         if( $t1 > $max1) $max1 = $t1;
        }
        return $max1 + 1;
      }
    }
}
